package com.bsz.patrol.controller;

import com.bsz.patrol.Service.ReportService;
import com.bsz.patrol.pojo.DailyReport;
import javafx.application.Application;
import javafx.geometry.Insets;  // 添加这一行
import javafx.scene.Scene;
import javafx.scene.control.Button;  // 添加这一行
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;  // 添加这一行
import javafx.scene.control.TextArea;  // 添加这一行
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;


import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

@Component
public class ReportApplication extends Application {

    @Autowired
    private ReportService reportService;

    private Stage primaryStage;

    // 在 ReportApplication 中添加静态上下文引用
    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext context) {
        applicationContext = context;
    }

    @Override
    public void start(Stage primaryStage) {
        this.primaryStage = primaryStage;
        createMainWindow();
    }

    private void createMainWindow() {
        VBox root = new VBox(10);
        root.setPadding(new Insets(15));

        // 日期选择
        Label dateLabel = new Label("选择日期:");
        DatePicker datePicker = new DatePicker(LocalDate.now());

        // 生成按钮
        Button generateBtn = new Button("生成报表");

        // 结果显示
        TextArea resultArea = new TextArea();
        resultArea.setPrefHeight(200);


        generateBtn.setOnAction(e -> {
            try {
                LocalDate selectedDate = datePicker.getValue();
                if (selectedDate == null) {
                    resultArea.setText("请选择日期");
                    return;
                }

                // 手动从 Spring 上下文获取 service
                ReportService service = applicationContext.getBean(ReportService.class);
                if (service == null) {
                    resultArea.setText("服务未初始化，请重启应用");
                    return;
                }

                List<DailyReport> reports = service.generateDailyReport(selectedDate.toString());
                // 创建日期格式化器
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
                // 完整显示所有字段
                StringBuilder sb = new StringBuilder();
                if (reports != null && !reports.isEmpty()) {
                    for (DailyReport report : reports) {
                        sb.append("=== ").append(report.getName()).append(" 日报 ===\n");


//                        sb.append("日期: ").append(report.getDate()).append("\n");
                        // 格式化日期显示
                        String formattedDate = "";
                        if (report.getDate() != null) {
                            formattedDate = dateFormat.format(report.getDate());
                        } else {
                            formattedDate = selectedDate.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
                        }
                        sb.append("日期: ").append(formattedDate).append("\n");

                        sb.append("设备安装总数: ").append(report.getTotalInstalledDevices()).append("\n");
                        sb.append("设备在线数: ").append(report.getTotalOnlineDevices()).append("\n");
                        sb.append("设备离线数: ").append(report.getTotalOfflineDevices()).append("\n");
                        sb.append("设备离线详情: ").append(report.getOfflineDetails()).append("\n");
                        sb.append("设备离线原因: ").append(report.getOfflineReason()).append("\n");
                        sb.append("设备离线处理方法: ").append(report.getOfflineSolution()).append("\n");
                        sb.append("告警总数: ").append(report.getTotalAlarms()).append("\n");
                        sb.append("昨日新增告警: ").append(report.getYesterdayNewAlarms()).append("\n");
                        sb.append("昨日新增真实告警: ").append(report.getYesterdayRealAlarms()).append("\n");
                        sb.append("昨日新增虚假告警: ").append(report.getYesterdayFalseAlarms()).append("\n");
                        sb.append("核实告警原因: ").append(report.getAlarmVerificationReason()).append("\n");
                        sb.append("可用睡眠报告: ").append(report.getUsableSleepReports()).append("\n");
                        sb.append("不可用睡眠报告: ").append(report.getUnusableSleepReports()).append("\n");
                        sb.append("昨日睡眠报告未生成情况: ").append(report.getYesterdayNoReportSituation()).append("\n");
                        sb.append("昨日睡眠报告未生成的床位: ").append(report.getYesterdayNoReportBeds()).append("\n");
                        sb.append("平板使用情况: ").append(report.getTabletUsage()).append("\n");
                        sb.append("平板使用反馈: ").append(report.getTabletFeedback()).append("\n");
                        sb.append("平板反馈处理: ").append(report.getTabletFeedbackProcess()).append("\n");
                        sb.append("现场情况: ").append(report.getOnsiteSituation()).append("\n");
                        sb.append("现场情况处理: ").append(report.getOnsiteProcess()).append("\n");
                        sb.append("现场情况处理结果: ").append(report.getOnsiteProcessResult()).append("\n");
                        sb.append("问题记录: ").append(report.getIssueRecord()).append("\n");
                        sb.append("----------------------------------------\n\n");
                    }
                } else {
                    sb.append("没有找到相关数据");
                }

                resultArea.setText(sb.toString());

            } catch (Exception ex) {
                resultArea.setText("错误: " + ex.getMessage());
                ex.printStackTrace();
            }
        });

        // 在 createMainWindow 方法中添加导出按钮
        Button exportBtn = new Button("导出Excel");

// 导出按钮事件处理
        exportBtn.setOnAction(e -> {
            try {
                LocalDate selectedDate = datePicker.getValue();
                if (selectedDate == null) {
                    resultArea.setText("请选择日期");
                    return;
                }

                // 从 Spring 上下文获取 service
                ReportService service = applicationContext.getBean(ReportService.class);
                if (service == null) {
                    resultArea.setText("服务未初始化，请重启应用");
                    return;
                }

                // 创建文件选择器
                FileChooser fileChooser = new FileChooser();
                fileChooser.setTitle("保存Excel文件");
                fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Excel文件", "*.xlsx"));
                fileChooser.setInitialFileName("智慧养老项目巡查" + selectedDate.toString() + ".xlsx");

                File file = fileChooser.showSaveDialog(primaryStage);
                if (file != null) {
                    // 导出到本地文件
                    exportToLocalExcel(service, selectedDate.toString(), file);
                    resultArea.setText("Excel文件已保存到: " + file.getAbsolutePath());
                }

            } catch (Exception ex) {
                resultArea.setText("导出失败: " + ex.getMessage());
                ex.printStackTrace();
            }
        });


// 更新界面组件添加
        root.getChildren().addAll(dateLabel, datePicker, generateBtn, exportBtn, resultArea);


        Scene scene = new Scene(root, 400, 300);
        primaryStage.setTitle("智慧养老项目巡查工具");
        primaryStage.setScene(scene);
        primaryStage.show();
    }


    // 添加导出到本地文件的方法
    private void exportToLocalExcel(ReportService service, String date, File file) throws Exception {
        List<DailyReport> reports = service.generateDailyReport(date);

        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("日常报告");

            // 创建表头
            Row headerRow = sheet.createRow(0);
            String[] headers = {"日期", "名称", "设备安装总数", "设备在线总数", "设备离线总数", "设备离线详情",
                    "设备离线原因", "设备离线处理方法", "告警总数", "昨日新增告警", "昨日新增真实告警",
                    "昨日新增虚假告警", "核实告警原因", "可用睡眠报告", "不可用睡眠报告",
                    "昨日睡眠报告未生成情况", "昨日睡眠报告未生成的床位", "平板使用情况",
                    "平板使用反馈", "平板反馈处理", "现场情况", "现场情况处理",
                    "现场情况处理结果", "问题记录"};

            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 创建居中对齐的单元格样式
            CellStyle centerCellStyle = workbook.createCellStyle();
            centerCellStyle.setAlignment(HorizontalAlignment.CENTER);
            centerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

            int rowNum = 1;
            for (DailyReport report : reports) {
                Row row = sheet.createRow(rowNum++);

                // 日期列 - 应用居中样式和日期格式
                Cell dateCell = row.createCell(0);
                dateCell.setCellValue(report.getDate() != null ? report.getDate() : new Date());

                // 设置日期格式并居中
                CellStyle dateCellStyle = workbook.createCellStyle();
                CreationHelper createHelper = workbook.getCreationHelper();
                dateCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy/mm/dd"));
                dateCellStyle.setAlignment(HorizontalAlignment.CENTER);
                dateCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                dateCell.setCellStyle(dateCellStyle);

                // 其他列应用居中样式
                Cell nameCell = row.createCell(1);
                nameCell.setCellValue(report.getName() != null ? report.getName() : "");
                nameCell.setCellStyle(centerCellStyle);

                Cell totalInstalledCell = row.createCell(2);
                totalInstalledCell.setCellValue(report.getTotalInstalledDevices() != null ? report.getTotalInstalledDevices() : 0);
                totalInstalledCell.setCellStyle(centerCellStyle);

                Cell totalOnlineCell = row.createCell(3);
                totalOnlineCell.setCellValue(report.getTotalOnlineDevices() != null ? report.getTotalOnlineDevices() : 0);
                totalOnlineCell.setCellStyle(centerCellStyle);

                Cell totalOfflineCell = row.createCell(4);
                totalOfflineCell.setCellValue(report.getTotalOfflineDevices() != null ? report.getTotalOfflineDevices() : 0);
                totalOfflineCell.setCellStyle(centerCellStyle);

                Cell offlineDetailsCell = row.createCell(5);
                offlineDetailsCell.setCellValue(report.getOfflineDetails() != null ? report.getOfflineDetails() : "");
                offlineDetailsCell.setCellStyle(centerCellStyle);

                Cell offlineReasonCell = row.createCell(6);
                offlineReasonCell.setCellValue(report.getOfflineReason() != null ? report.getOfflineReason() : "");
                offlineReasonCell.setCellStyle(centerCellStyle);

                Cell offlineSolutionCell = row.createCell(7);
                offlineSolutionCell.setCellValue(report.getOfflineSolution() != null ? report.getOfflineSolution() : "");
                offlineSolutionCell.setCellStyle(centerCellStyle);

                Cell totalAlarmsCell = row.createCell(8);
                totalAlarmsCell.setCellValue(report.getTotalAlarms() != null ? report.getTotalAlarms() : 0);
                totalAlarmsCell.setCellStyle(centerCellStyle);

                Cell yesterdayNewAlarmsCell = row.createCell(9);
                yesterdayNewAlarmsCell.setCellValue(report.getYesterdayNewAlarms() != null ? report.getYesterdayNewAlarms() : 0);
                yesterdayNewAlarmsCell.setCellStyle(centerCellStyle);

                Cell yesterdayRealAlarmsCell = row.createCell(10);
                yesterdayRealAlarmsCell.setCellValue(report.getYesterdayRealAlarms() != null ? report.getYesterdayRealAlarms() : "");
                yesterdayRealAlarmsCell.setCellStyle(centerCellStyle);

                Cell yesterdayFalseAlarmsCell = row.createCell(11);
                yesterdayFalseAlarmsCell.setCellValue(report.getYesterdayFalseAlarms() != null ? report.getYesterdayFalseAlarms() : "");
                yesterdayFalseAlarmsCell.setCellStyle(centerCellStyle);

                Cell alarmVerificationReasonCell = row.createCell(12);
                alarmVerificationReasonCell.setCellValue(report.getAlarmVerificationReason() != null ? report.getAlarmVerificationReason() : "");
                alarmVerificationReasonCell.setCellStyle(centerCellStyle);

                Cell usableSleepReportsCell = row.createCell(13);
                usableSleepReportsCell.setCellValue(report.getUsableSleepReports() != null ? report.getUsableSleepReports() : 0);
                usableSleepReportsCell.setCellStyle(centerCellStyle);

                Cell unusableSleepReportsCell = row.createCell(14);
                unusableSleepReportsCell.setCellValue(report.getUnusableSleepReports() != null ? report.getUnusableSleepReports() : 0);
                unusableSleepReportsCell.setCellStyle(centerCellStyle);

                Cell yesterdayNoReportSituationCell = row.createCell(15);
                yesterdayNoReportSituationCell.setCellValue(report.getYesterdayNoReportSituation() != null ? report.getYesterdayNoReportSituation() : "");
                yesterdayNoReportSituationCell.setCellStyle(centerCellStyle);

                Cell yesterdayNoReportBedsCell = row.createCell(16);
                yesterdayNoReportBedsCell.setCellValue(report.getYesterdayNoReportBeds() != null ? report.getYesterdayNoReportBeds() : "");
                yesterdayNoReportBedsCell.setCellStyle(centerCellStyle);

                Cell tabletUsageCell = row.createCell(17);
                tabletUsageCell.setCellValue(report.getTabletUsage() != null ? report.getTabletUsage() : "");
                tabletUsageCell.setCellStyle(centerCellStyle);

                Cell tabletFeedbackCell = row.createCell(18);
                tabletFeedbackCell.setCellValue(report.getTabletFeedback() != null ? report.getTabletFeedback() : "");
                tabletFeedbackCell.setCellStyle(centerCellStyle);

                Cell tabletFeedbackProcessCell = row.createCell(19);
                tabletFeedbackProcessCell.setCellValue(report.getTabletFeedbackProcess() != null ? report.getTabletFeedbackProcess() : "");
                tabletFeedbackProcessCell.setCellStyle(centerCellStyle);

                Cell onsiteSituationCell = row.createCell(20);
                onsiteSituationCell.setCellValue(report.getOnsiteSituation() != null ? report.getOnsiteSituation() : "");
                onsiteSituationCell.setCellStyle(centerCellStyle);

                Cell onsiteProcessCell = row.createCell(21);
                onsiteProcessCell.setCellValue(report.getOnsiteProcess() != null ? report.getOnsiteProcess() : "");
                onsiteProcessCell.setCellStyle(centerCellStyle);

                Cell onsiteProcessResultCell = row.createCell(22);
                onsiteProcessResultCell.setCellValue(report.getOnsiteProcessResult() != null ? report.getOnsiteProcessResult() : "");
                onsiteProcessResultCell.setCellStyle(centerCellStyle);

                Cell issueRecordCell = row.createCell(23);
                issueRecordCell.setCellValue(report.getIssueRecord() != null ? report.getIssueRecord() : "");
                issueRecordCell.setCellStyle(centerCellStyle);
            }

            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }

            // 写入文件
            try (FileOutputStream fileOut = new FileOutputStream(file)) {
                workbook.write(fileOut);
            }
        }
    }
}

